package com.tepth.repair.bugly;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.support.multidex.MultiDex;

import com.joanzapata.iconify.fonts.FontAwesomeModule;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.zhangyu.shadow.repair.config.ServiceUrl;
import com.zhangyu.shadow.repair.icon.FontEcModule;

import java.util.List;
import java.util.WeakHashMap;

import st.lib.base.Shadow;
import st.lib.base.itf.IComponentApplication;
import st.lib.base.net.interceptors.AddCookieInterceptor;
import st.lib.base.util.utilcode.util.ScreenUtils;
import st.lib.base.util.utilcode.util.Utils;

/**
 * @author zhangyu
 * @date 2018/3/13
 */

public class MyApplication extends Application implements
        Application.ActivityLifecycleCallbacks {
    private static final String TAG = "MyApplication";
    private static final String APP_ID = "a0235eb25d";
    //组件模块初始化
    private static final String[] MODULES_LIST =
            {"com.zhangyu.shadow.repair.init.RepairComponent"};
    private WeakHashMap<String, IComponentApplication> mApplicationWeakHashMap
            = new WeakHashMap<>();

    @SuppressWarnings("DanglingJavadoc")
    @Override
    public void onCreate() {
        super.onCreate();
        initTinker();
        //检测是否存在内存泄漏
//        LeakCanary.install(this);
        Shadow.init(this)
//                .withApiHost(ShadowPreference.getAppFlag(SpKey.IS_DEBUG) ?
//                        ServiceUrl.BASE_DEBUG_URL : ServiceUrl.BASE_RELEASE_URL)
                //.withApiHost(ServiceUrl.BASE_DEBUG_URL)
                .withApiHost(ServiceUrl.BASE_RELEASE_URL)
                .withIcon(new FontAwesomeModule())
                .withIcon(new FontEcModule())
                .withInterceptor(new AddCookieInterceptor())
                //.withInterceptor(new LoggingInterceptor(true))
                .configure();
        modulesApplicationInit();
        registerActivityLifecycleCallbacks(this);
        Utils.init(this);
//        ThemeManager.init(this, 2, 0, null);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        if (isMain()) {
            // you must install multiDex whatever tinker is installed!
            MultiDex.install(base);
            // 安装tinker
            // Beta.installTinker();
            if (mApplicationWeakHashMap != null) {
                for (String key : mApplicationWeakHashMap.keySet()) {
                    mApplicationWeakHashMap.get(key).attachBaseContext(base);
                }
            }
        }
    }

    private void modulesApplicationInit() {
        for (String moduleImpl : MODULES_LIST) {
            try {
                Class<?> clazz = Class.forName(moduleImpl);
                Object obj = clazz.newInstance();
                if (obj instanceof IComponentApplication) {
                    ((IComponentApplication) obj).onCreate(this);
                    mApplicationWeakHashMap.put(moduleImpl, (IComponentApplication) obj);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null) {
            List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
            if (runningApps == null) {
                return null;
            }
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
        }
        return null;
    }

    /**
     * 初始化bugly
     */
    private void initTinker() {
        Beta.autoInit = true;
        Beta.autoCheckUpgrade = true;
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        Bugly.init(this, APP_ID, false);
    }

    /**
     * 是否为主进程
     */
    private boolean isMain() {
        String processName = getProcessName(this, android.os.Process.myPid());
        return processName != null && processName.equals(getPackageName());
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        if (ScreenUtils.isPad(this)) {
            // 禁止字体大小随系统设置变化
            Resources resources = activity.getResources();
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.2f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
